import {initTRPC, TRPCError} from "@trpc/server";
import {getServerSession} from "@/server/auth";
import {createCallerFactory} from "@trpc/server/unstable-core-do-not-import";

export async function createTRPCContext(){
    const session = await getServerSession()
    return  {session}
}
const t = initTRPC.context<typeof createTRPCContext>().create()
const {router,procedure} = t
const middleware = t.middleware(async ({ctx,next})=>{
    const start = Date.now();
    const result = await next();
    console.log("请求结果",result);
    console.log("请求结果耗时",Date.now()-start);
    return result;
})
//校验登录，拆出来是因为有些页面无需登录
const checkLoginMiddleware=t.middleware(async ({ctx,next})=>{
    if(!ctx?.session?.user){
    throw new TRPCError({
        code:"FORBIDDEN"
    })
    }
    return next();
})
const loggedProcedure = procedure.use(middleware);
const protectedProcedure = procedure.use(checkLoginMiddleware);
export const testRouter = router({
    hello:loggedProcedure.query(async ({ctx})=>{
        console.log('session',ctx?.session)
        await new Promise((resolve,reject)=>{
            setTimeout(()=>{
                resolve(true);
            },1000)
        })
        return {
            hello:'world'
        }
    })
})
export type TestRouter = typeof testRouter
export const serverCaller = createCallerFactory()(testRouter)
